package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.autoconfig.template.AipFaceTemlate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.Question;
import com.tanhua.model.domain.Settings;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class SettingsService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SmsTemplate smsTemplate;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private SettingsApi settingsApi;

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private BlackListApi blackListApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemlate aipFaceTemlate;

    /**
     * 获取通用设置中的详细信息
     *
     * @return
     */
    public SettingsVo settings() {
        SettingsVo vo = new SettingsVo();
        //1、从线程空间中获取用户的id和电话
        Long userId = UserHolder.getUserId();
        String mobile = UserHolder.getMobile();
        vo.setId(userId);
        vo.setPhone(mobile);
        //没有设置信息则设置默认
        //获取用户的陌生人问题
        Question question = questionApi.findByUserId(userId);
        String txt = question == null ? "你喜欢我吗?" : question.getTxt();
        vo.setStrangerQuestion(txt);
        //调用方法获取信息
        Settings settings = settingsApi.findByUserId(userId);
        //获取用户的APP通知开关数据
        if (settings != null) {
            vo.setGonggaoNotification(settings.getGonggaoNotification());
            vo.setLikeNotification(settings.getLikeNotification());
            vo.setPinglunNotification(settings.getPinglunNotification());
        }

        return vo;
    }

    /**
     * 设置陌生人问题
     *
     * @param content
     */
    public void saveQuestion(String content) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //从数据库中获取陌生人问题
        Question question = questionApi.findByUserId(userId);
        if (question == null) {
            question = new Question();
            //没有添加陌生人问题
            question.setUserId(userId);
            question.setTxt(content);
//            questionApi.save(question);
            questionApi.myPostQuestion(question);
        }
        //有则更新
        question.setUserId(userId);
        question.setTxt(content);
//        questionApi.update(question);
        questionApi.myPutQuestion(question);

    }

    /**
     * 通知设置
     */
    public void saveSettings(Map map) {
        log.info("当前通知设置{}", map);
        boolean likeNotification = (boolean) map.get("likeNotification");
        boolean pinglunNotification = (boolean) map.get("pinglunNotification");
        boolean gonggaoNotification = (boolean) map.get("gonggaoNotification");
        //获取用户id
        Long userId = UserHolder.getUserId();
        //查看当前用户是否设置过通知
        Settings settings = settingsApi.findByUserId(userId);
        if (settings != null) {
            //设置过更新
            settings.setUserId(userId);
            settings.setGonggaoNotification(gonggaoNotification);
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settingsApi.update(settings);
        } else {
            settings = new Settings();
            settings.setGonggaoNotification(gonggaoNotification);
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            //没设置过添加
            settings.setUserId(userId);
            settingsApi.save(settings);
        }

    }

    public PageResult blacklist(Integer page, Integer pagesize) {
        //1、获取当前用户的id
        Long userId = UserHolder.getUserId();
        //2、调用API查询用户的黑名单分页列表  Ipage对象
        IPage<UserInfo> iPage = blackListApi.findByUserId(userId, page, pagesize);
        //3、对象转化，将查询的Ipage对象的内容封装到PageResult中
        PageResult result = new PageResult(page, pagesize, Math.toIntExact(iPage.getTotal()), iPage.getRecords());
        //4、返回
        return result;
    }

    public void deleteBlackList(Long blackUserId) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、调用api删除
        blackListApi.deleteBlackList(userId, blackUserId);
    }

    //发送验证码
    public ResponseEntity sendVerificationCode() {
        //从线程空间中获取手机号
        String phone = UserHolder.getMobile();
        //设置验证码
        //1、随机生成6位数字
//        String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        //获取当前时间
        Long currentTime = System.currentTimeMillis();
        //从redis中获取验证码，看是否为空，为空则没有发送过验证码，不为空则获取验证码发送时间
        String updatePhoneCode = (String) redisTemplate.opsForValue().get("UPDATE_PHONE_CODE_" + phone);
        if (updatePhoneCode != null) {
            if ((Long.valueOf(updatePhoneCode.split("_")[1]) - currentTime) < 10 * 1000) {
                return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body("请10秒后再次点击发送验证码！");
            }
        }
        //调用接口发送验证码
//        smsTemplate.sendSms(phone,code);
        //向redis中缓存验证码并设置当前时间,验证吗保存5分钟
        redisTemplate.opsForValue().set("UPDATE_PHONE_CODE_" + phone, code + "_" + currentTime, Duration.ofMinutes(5));

        return ResponseEntity.ok(null);
    }


    /**
     * 校验验证码是否正确
     *
     * @param code
     */
    public ResponseEntity checkVerificationCode(String code) {
//从线程空间中获取当前登录手机号
        String phone = UserHolder.getMobile();
        //        从缓存中获取验证码
        String redisCode = (String) redisTemplate.opsForValue().get("UPDATE_PHONE_CODE_" + phone);
//                分解验证码
        Map map = new HashMap();
//                校验验证码是否正确
        if (StringUtils.isEmpty(redisCode) || redisCode.split("_")[0].equals(code)) {
            map.put("verification", true);
            redisTemplate.delete("UPDATE_PHONE_CODE_" + phone);
            return ResponseEntity.ok(map);
        }
        map.put("verification", false);
        return ResponseEntity.ok(map);
    }

    /**
     * 修改手机号
     *
     * @param phone
     */
    public void phoneUpdate(String phone) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //封装用户信息
        User user = new User();
        user.setId(userId);
        user.setMobile(phone);
        userApi.update(user);
    }

    /**
     * 更新用户头像
     * @param headPhoto
     * @throws IOException
     */
    public void updateHeader(MultipartFile headPhoto) throws IOException {
//        获取当前用户id
        Long userId = UserHolder.getUserId();
//                上传图片文件获取url
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
//        校验是否是人脸
//        boolean detect = aipFaceTemlate.detect(imageUrl);
//                查询当前用户详细信息
        UserInfo byId = userInfoApi.findById(userId);
//        更改url
        byId.setAvatar(imageUrl);
//                更新用户信息
        userInfoApi.update(byId);
    }
}
